package com.we.flink.userlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.userlabelplatform.table.TableTieCardRiskTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagTieCardRiskTag {
    public long uid;
    public int tiecard_risk_tag_output_time;
    public int tiecard_risk_tag_vaild_time;

    public TagTieCardRiskTag(
            long uid, int tiecard_risk_tag_output_time, int tiecard_risk_tag_vaild_time) {
        this.uid = uid;
        this.tiecard_risk_tag_output_time = tiecard_risk_tag_output_time;
        this.tiecard_risk_tag_vaild_time = tiecard_risk_tag_vaild_time;
    }

    public static TagTieCardRiskTag init(long uid) {
        return new TagTieCardRiskTag(uid, 0, 0);
    }

    public static Logger LOG = LoggerFactory.getLogger(TagTieCardRiskTag.class);

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableTieCardRiskTag.QUERYSQL);
        DataStream<Tuple2<Boolean, TableTieCardRiskTag>> inputStream =
                tableEnv.toRetractStream(tableRes, TableTieCardRiskTag.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableTieCardRiskTag>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableTieCardRiskTag> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagTieCardRiskTag-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableTieCardRiskTag>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableTieCardRiskTag> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableTieCardRiskTag>, String>() {
                                    ValueState<TagTieCardRiskTag> tagTieCardRiskTagVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tagTieCardRiskTagVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagTieCardRiskTag>(
                                                                        "TagTieCardRiskTagVState",
                                                                        TagTieCardRiskTag.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableTieCardRiskTag> value,
                                            Collector<String> out)
                                            throws Exception {
                                        int update_time =
                                                (int) (value.f1.getUpdate_time().getTime() / 1000);
                                        int tiecard_risk_tag_vaild_time =
                                                (int)
                                                        (value.f1.getShow_valid_date().getTime()
                                                                / 1000);
                                        long uid = value.f1.getUid();

                                        TagTieCardRiskTag tmpState =
                                                tagTieCardRiskTagVState.value();
                                        TagTieCardRiskTag curState =
                                                tmpState == null
                                                        ? TagTieCardRiskTag.init(uid)
                                                        : tmpState;

                                        if (curState.getTiecard_risk_tag_output_time()
                                                < update_time) {
                                            curState.tiecard_risk_tag_output_time = update_time;
                                            curState.tiecard_risk_tag_vaild_time =
                                                    tiecard_risk_tag_vaild_time;

                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("uid", uid);
                                            jsonObject.put(
                                                    "tiecard_risk_tag_output_time",
                                                    curState.tiecard_risk_tag_output_time);
                                            /** tiecard_risk_tag_vaild_time 0 -> null */
                                            jsonObject.put(
                                                    "tiecard_risk_tag_vaild_time",
                                                    (curState.tiecard_risk_tag_vaild_time == 0
                                                            ? null
                                                            : curState.tiecard_risk_tag_vaild_time));

                                            out.collect(jsonObject.toString());
                                            tagTieCardRiskTagVState.update(curState);
                                        }
                                    }
                                });

        return out;
    }

    public int getTiecard_risk_tag_output_time() {
        return tiecard_risk_tag_output_time;
    }

    public int getTiecard_risk_tag_vaild_time() {
        return tiecard_risk_tag_vaild_time;
    }
}
